package com.masterclient.app.modules.aftersale;

import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselibrary.base.FragmentHostActivity;
import com.eoner.baselibrary.bean.aftersale.AfterSaleItemBean;
import com.eoner.baselibrary.bean.aftersale.AfterSaleServeInfoBean;
import com.eoner.baselibrary.bean.aftersale.IncomeCommisssionFilterBean;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.aftersale.adapter.AfterSaleServeAdapter;
import com.masterclient.app.modules.aftersale.contract.AfterSaleServeContract;
import com.masterclient.app.modules.aftersale.contract.AfterSaleServePresenter;
import com.eoner.uikit.header.MyRefreshHead;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = AroutePath.AFTER_SALE_SERVE_FRAGMENT)
public class AfterSaleServeFragment extends BaseFragment<AfterSaleServePresenter> implements AfterSaleServeContract.View {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.view_head)
    View viewHead;
    @BindView(R.id.view_empty)
    View emptyView;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_reload)
    TextView tvReload;

    private AfterSaleServeAdapter afterSaleServeAdapter;
    private AfterSaleServePopupWindow popupWindow;
    private List<IncomeCommisssionFilterBean> popList = new ArrayList<>();
    private List<AfterSaleItemBean> list = new ArrayList<>();
    private View footView;
    private int page = 1;
    private String status = "10";
    private boolean hasMore;

    public static AfterSaleServeFragment newInstance() {
        return new AfterSaleServeFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_after_sale_serve, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        refreshLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getAfterSaleServeList(status, page + "", PAGE_SIZE);
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        afterSaleServeAdapter = new AfterSaleServeAdapter(id -> {
            Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.REFUND_DETAILS_FRAGMENT)
                    .withString("refundNo",id)
                    .navigation();
            FragmentHostActivity.openFragment(mContext, fragment);
        });
        recyclerView.setAdapter(afterSaleServeAdapter);
        afterSaleServeAdapter.bindToRecyclerView(recyclerView);

        emptyView.setVisibility(View.GONE);
        footView = View.inflate(mContext, R.layout.view_foot_text, null);
        footView.setVisibility(View.GONE);
        View viewFooter = footView.findViewById(R.id.view_footer);
        viewFooter.setBackgroundColor(Color.parseColor("#00000000"));
        afterSaleServeAdapter.setFooterView(footView);
        afterSaleServeAdapter.setOnLoadMoreListener(() -> {
            if (hasMore) {
                page++;
                mPresenter.getAfterSaleServeList(status, String.valueOf(page), PAGE_SIZE);
            }
        }, recyclerView);
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        mPresenter.getAfterSaleServeList(status, String.valueOf(page), PAGE_SIZE);
    }

    @OnClick({R.id.rl_back, R.id.tv_filtrate})
    void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.rl_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
            case R.id.tv_filtrate:
                displayPopupWindow();
                break;
        }
    }

    private void displayPopupWindow() {
        if (popupWindow == null) {
            popupWindow = new AfterSaleServePopupWindow(getActivity(), popList, new AfterSaleServePopupWindow.CallBack() {
                @Override
                public void dismiss() {

                }

                @Override
                public void OnSelect(IncomeCommisssionFilterBean tabBean) {
                    page = 1;
                    status = tabBean.getType();
                    mPresenter.getAfterSaleServeList(status, page + "", PAGE_SIZE);
                    dismissPopupWindow();
                }
            });
        }
        popupWindow.showAsDropDown(viewHead);
        popupWindow.setOutsideTouchable(true);
    }

    private void dismissPopupWindow() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    @Override
    public void showAfterSaleServeInfo(AfterSaleServeInfoBean bean) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }

        setEmptyStatus(3);
        if (bean.statusMap != null) {
            // 遍历键值对对象的集合，得到每一个键值对对象
            popList.clear();
            for (Map.Entry<String, String> me : bean.statusMap.entrySet()) {
                // 根据键值对对象获取键和值
                IncomeCommisssionFilterBean popBean = new IncomeCommisssionFilterBean();
                popBean.setType(me.getKey());
                popBean.setName(me.getValue());
                popList.add(popBean);
            }
        }
        hasMore = bean.refundList.size() > 0;
        if (list == null) {
            list = new ArrayList<>();
        }
        if (page == 1) {
            list.clear();
        }

        list.addAll(bean.refundList);
        afterSaleServeAdapter.setNewData(list);
        if (list.size() <= 0) {
            setEmptyStatus(2);
        }
        if (list.size() > 0 && !hasMore) {
            afterSaleServeAdapter.setEnableLoadMore(false);
            if (page != 1) {
                footView.setVisibility(View.VISIBLE);
            }
        } else {
            footView.setVisibility(View.GONE);
        }
        afterSaleServeAdapter.notifyDataSetChanged();
    }

    @Override
    public void showFail(String msg) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh(false);
        }
        setEmptyStatus(1);
    }

    /**
     * 设置页面置空状态
     *
     * @param status status == 1：code=15，页面加载失败
     *               status == 2：数据返回为空
     *               status == 3：数据返回正常
     */
    private void setEmptyStatus(int status) {
        if (status == 1) {
            emptyView.setVisibility(View.VISIBLE);
            tvTip.setText("页面加载失败～");
            tvReload.setVisibility(View.GONE);
        } else if (status == 2) {
            emptyView.setVisibility(View.VISIBLE);
            tvTip.setText("暂无数据");
            tvReload.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }
}
